import os
import yaml
from os import path
from os.path import sep
import openpyxl


class creat_485config:
    def __init__(self) -> None:
        #上一层目录config为配置文件目录
        self.config_dir = path.dirname(path.dirname(__file__)) + "/config".replace("/",sep)
        #打开表格设备信息表
        self.wb = openpyxl.load_workbook(self.config_dir + "/设备信息.xlsx".replace("/",sep))
        #获取485设备列表sheet
        self._485sheet = self.wb["485设备列表"]
        self.devlist = self._get_485dev()
        with open(self.config_dir + "/rs485tomqtt.yaml_template".replace("/",sep),"r",encoding="utf-8") as f:
            self._485config = yaml.load(f,Loader=yaml.FullLoader)
            #规则打印
            print(yaml.dump(self._485config))
        pass
    def _get_485dev(self):
        #获取485设备列表
        dev_tag = []
        for cell in self._485sheet[1]:
            if cell.value == None:
                break
            dev_tag.append(cell.value)
        #第二行开始获取485设备列表的值
        dev_list = []
        for row in self._485sheet.rows:
            if row[0].value == None:
                continue
            dev = {}
            for i in range(len(dev_tag)):
                dev[dev_tag[i]] = row[i].value
            dev_list.append(dev)
        return dev_list
    
    def creat_rs485(self,type):
        if type == "modbus":
            if self._485config["rs485"].get("modbus_slaves") == None:
                self._485config["rs485"]["modbus_slaves"] = []
            self._485config["rs485"]["modbus_slaves"] = self._get_modbus_dev()

            pass
        elif type == "645":
            pass

    def _get_modbus_dev(self):
        iddict = {}
        namedict = {}
        modlist = []
        modbus_slaves_list = []
        for dev in self.devlist:
            if dev["设备类型"] == "modbus":
                modlist.append(dev)
        
        serial_dev = {}
        for dev in modlist:
            if dev["串口服务器"] in serial_dev:
                serial_dev[dev["串口服务器"]].append(dev)
            else:
                serial_dev[dev["串口服务器"]] = [dev]
        for key in serial_dev:
            temp = {
                "host": key,
                "port": 5000,
                "type": "tcp",
                "timeout": 40,
                "method": "rtu",
                "byteOrder": "BIG",
                "wordOrder": "BIG"
            }
            for dev in serial_dev[key]:
                if temp.get("devices") == None:
                    temp["devices"] = []
                if dev["id"] in iddict:
                    print("id重复:",dev["id"])
                    continue
                else:
                    iddict[dev["id"]] = dev
                if dev["名字"] in namedict:
                    print("名字重复:",dev["名字"])
                    continue
                else:
                    namedict[dev["名字"]] = dev

                temp["devices"].append({
                    "addr": dev["id"],
                    "name": dev["名字"],
                    "type": "emeter/DTSU6606",
                    "attrPoll": 6000,
                    "tsPoll": 500,
                    "attr": [{"key":"loadpower",
                              "data": 50}],
                    "ts": [{"key":"electricity",
                            "factor": 1}]
                })
            modbus_slaves_list.append(temp)
        print(modbus_slaves_list)
        return modbus_slaves_list
    
    def _get_645_dev(self):
        devlist = []
        for dev in self.devlist:
            if dev["设备类型"] == "645":
                devlist.append(dev)
        return devlist
    
    def start(self):
        self.creat_rs485("modbus")
        #按照规律写入yaml
        with open(self.config_dir + "/rs485tomqtt.yaml".replace("/",sep),"w",encoding="utf-8") as f:
            yaml.dump(self._485config,f)
        pass

if __name__ == "__main__":
    creat_485config().start()
    pass